package com.yonyou.pmclouds.basecom.aspect;

import com.yonyou.pmclouds.basecom.entity.SuperVO;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.basecom.util.BeanHelper;
import com.yonyou.pmclouds.basecom.util.CommonFieldConst;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * 新增方法切面处理类，给VO设置创建人，处理服务端RuntimeEnvironment中的userId丢失问题
 *
 * @author th
 * @date 2019/11/4 10:28
 */
@Aspect
@Slf4j
@Component
public class BeforeInsertAspect {

    @Pointcut("@annotation(com.yonyou.pmclouds.basecom.annotation.Insert)")
    public void insertPointCut() {
    }

    @Around("insertPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Object[] args = point.getArgs();
        if (ArrayUtils.isEmpty(args) || !(args[0] instanceof SuperVO))
            throw new BusinessException("@Insert标记的方法第一个参数必须是SuperVO");

        String userId = RuntimeEnvironment.getLoginUserId();
        if (StringUtils.isEmpty(userId)) {
            log.info("consumer的RuntimeEnvironment中的userId为空，方法名：{}", point.getSignature().getName());
        }

        Object vo = args[0];
        // 设置创建人
        BeanHelper.setProperty(vo, CommonFieldConst.CREATOR, userId);

        return point.proceed(args);
    }
}
